package com.datagateway.controller;

import com.datagateway.component.DataValidationEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 数据校验控制器
 * 提供数据校验规则引擎相关的REST API接口
 * 
 * @author Data Gateway Team
 * @version 1.0.0
 */
@RestController
@RequestMapping("/data-gateway/api/data-validation")
public class DataValidationController {

    @Autowired
    private DataValidationEngine dataValidationEngine;

    /**
     * 校验数据
     * 
     * @param request 校验请求
     * @return 校验结果
     */
    @PostMapping("/validate")
    public Map<String, Object> validateData(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String data = (String) request.get("data");
            String ruleSetName = (String) request.get("ruleSetName");
            
            if (data == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数: data");
                return result;
            }
            
            if (ruleSetName == null) {
                ruleSetName = "default";
            }
            
            DataValidationEngine.ValidationResult validationResult = dataValidationEngine.validate(data, ruleSetName);
            
            result.put("success", true);
            result.put("valid", validationResult.isValid());
            result.put("status", validationResult.getStatus());
            result.put("message", validationResult.getMessage());
            result.put("errors", validationResult.getErrors());
            result.put("ruleSetName", ruleSetName);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "数据校验异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 批量校验数据
     * 
     * @param request 批量校验请求
     * @return 校验结果列表
     */
    @PostMapping("/batch-validate")
    public Map<String, Object> batchValidateData(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            @SuppressWarnings("unchecked")
            List<String> dataList = (List<String>) request.get("dataList");
            String ruleSetName = (String) request.get("ruleSetName");
            
            if (dataList == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数: dataList");
                return result;
            }
            
            if (ruleSetName == null) {
                ruleSetName = "default";
            }
            
            List<DataValidationEngine.ValidationResult> validationResults = dataValidationEngine.batchValidate(dataList, ruleSetName);
            
            result.put("success", true);
            result.put("results", validationResults);
            result.put("count", validationResults.size());
            result.put("ruleSetName", ruleSetName);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量数据校验异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 创建校验规则
     * 
     * @param request 创建规则请求
     * @return 操作结果
     */
    @PostMapping("/rules")
    public Map<String, Object> createValidationRule(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String ruleName = (String) request.get("ruleName");
            String ruleType = (String) request.get("ruleType");
            String fieldPath = (String) request.get("fieldPath");
            @SuppressWarnings("unchecked")
            Map<String, Object> ruleConfig = (Map<String, Object>) request.get("ruleConfig");
            
            if (ruleName == null || ruleType == null || fieldPath == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数: ruleName, ruleType, fieldPath");
                return result;
            }
            
            boolean success = dataValidationEngine.createValidationRule(ruleName, ruleType, fieldPath, ruleConfig);
            
            result.put("success", success);
            result.put("message", success ? "校验规则创建成功" : "校验规则创建失败");
            result.put("ruleName", ruleName);
            result.put("ruleType", ruleType);
            result.put("fieldPath", fieldPath);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建校验规则异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 创建校验规则集
     * 
     * @param request 创建规则集请求
     * @return 操作结果
     */
    @PostMapping("/rule-sets")
    public Map<String, Object> createValidationRuleSet(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String ruleSetName = (String) request.get("ruleSetName");
            @SuppressWarnings("unchecked")
            List<String> ruleNames = (List<String>) request.get("ruleNames");
            String description = (String) request.get("description");
            
            if (ruleSetName == null || ruleNames == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数: ruleSetName, ruleNames");
                return result;
            }
            
            boolean success = dataValidationEngine.createValidationRuleSet(ruleSetName, ruleNames, description);
            
            result.put("success", success);
            result.put("message", success ? "校验规则集创建成功" : "校验规则集创建失败");
            result.put("ruleSetName", ruleSetName);
            result.put("ruleCount", ruleNames.size());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建校验规则集异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取校验规则
     * 
     * @param ruleName 规则名称
     * @return 校验规则
     */
    @GetMapping("/rules/{ruleName}")
    public Map<String, Object> getValidationRule(@PathVariable String ruleName) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DataValidationEngine.ValidationRule rule = dataValidationEngine.getValidationRule(ruleName);
            
            if (rule != null) {
                result.put("success", true);
                result.put("rule", rule);
            } else {
                result.put("success", false);
                result.put("message", "校验规则不存在");
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取校验规则异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取校验规则集
     * 
     * @param ruleSetName 规则集名称
     * @return 校验规则集
     */
    @GetMapping("/rule-sets/{ruleSetName}")
    public Map<String, Object> getValidationRuleSet(@PathVariable String ruleSetName) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DataValidationEngine.ValidationRuleSet ruleSet = dataValidationEngine.getValidationRuleSet(ruleSetName);
            
            if (ruleSet != null) {
                result.put("success", true);
                result.put("ruleSet", ruleSet);
            } else {
                result.put("success", false);
                result.put("message", "校验规则集不存在");
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取校验规则集异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取所有校验规则
     * 
     * @return 校验规则列表
     */
    @GetMapping("/rules")
    public Map<String, Object> getAllValidationRules() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<DataValidationEngine.ValidationRule> rules = dataValidationEngine.getAllValidationRules();
            
            result.put("success", true);
            result.put("rules", rules);
            result.put("count", rules.size());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取校验规则列表异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取所有校验规则集
     * 
     * @return 校验规则集列表
     */
    @GetMapping("/rule-sets")
    public Map<String, Object> getAllValidationRuleSets() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<DataValidationEngine.ValidationRuleSet> ruleSets = dataValidationEngine.getAllValidationRuleSets();
            
            result.put("success", true);
            result.put("ruleSets", ruleSets);
            result.put("count", ruleSets.size());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取校验规则集列表异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 删除校验规则
     * 
     * @param ruleName 规则名称
     * @return 操作结果
     */
    @DeleteMapping("/rules/{ruleName}")
    public Map<String, Object> removeValidationRule(@PathVariable String ruleName) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = dataValidationEngine.removeValidationRule(ruleName);
            
            result.put("success", success);
            result.put("message", success ? "校验规则删除成功" : "校验规则删除失败");
            result.put("ruleName", ruleName);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除校验规则异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 删除校验规则集
     * 
     * @param ruleSetName 规则集名称
     * @return 操作结果
     */
    @DeleteMapping("/rule-sets/{ruleSetName}")
    public Map<String, Object> removeValidationRuleSet(@PathVariable String ruleSetName) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = dataValidationEngine.removeValidationRuleSet(ruleSetName);
            
            result.put("success", success);
            result.put("message", success ? "校验规则集删除成功" : "校验规则集删除失败");
            result.put("ruleSetName", ruleSetName);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除校验规则集异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取校验统计信息
     * 
     * @return 统计信息
     */
    @GetMapping("/statistics")
    public Map<String, Object> getValidationStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DataValidationEngine.ValidationStatistics stats = dataValidationEngine.getStatistics();
            
            result.put("success", true);
            result.put("statistics", stats);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取校验统计异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 设置校验配置
     * 
     * @param request 配置请求
     * @return 操作结果
     */
    @PostMapping("/config")
    public Map<String, Object> setValidationConfiguration(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Boolean enabled = (Boolean) request.get("enabled");
            Boolean strictMode = (Boolean) request.get("strictMode");
            Boolean stopOnFirstError = (Boolean) request.get("stopOnFirstError");
            Integer maxValidationDepth = (Integer) request.get("maxValidationDepth");
            Long validationTimeout = ((Number) request.get("validationTimeout")).longValue();
            
            if (enabled == null || strictMode == null || stopOnFirstError == null || 
                maxValidationDepth == null || validationTimeout == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数");
                return result;
            }
            
            dataValidationEngine.setConfiguration(enabled, strictMode, stopOnFirstError, 
                maxValidationDepth, validationTimeout);
            
            result.put("success", true);
            result.put("message", "校验配置设置成功");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "设置校验配置异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取校验配置
     * 
     * @return 配置信息
     */
    @GetMapping("/config")
    public Map<String, Object> getValidationConfiguration() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DataValidationEngine.ValidationStatistics stats = dataValidationEngine.getStatistics();
            
            Map<String, Object> config = new HashMap<>();
            config.put("enabled", stats.isValidationEnabled());
            config.put("strictMode", stats.isStrictMode());
            config.put("stopOnFirstError", stats.isStopOnFirstError());
            config.put("maxValidationDepth", stats.getMaxValidationDepth());
            config.put("validationTimeout", stats.getValidationTimeout());
            
            result.put("success", true);
            result.put("config", config);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取校验配置异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 测试数据校验
     * 
     * @param request 测试请求
     * @return 测试结果
     */
    @PostMapping("/test")
    public Map<String, Object> testDataValidation(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String ruleSetName = (String) request.get("ruleSetName");
            String dataType = (String) request.get("dataType");
            
            if (ruleSetName == null) {
                ruleSetName = "default";
            }
            
            if (dataType == null) {
                dataType = "user";
            }
            
            // 生成测试数据
            String testData = generateTestData(dataType);
            
            // 执行校验
            DataValidationEngine.ValidationResult validationResult = dataValidationEngine.validate(testData, ruleSetName);
            
            result.put("success", true);
            result.put("testData", testData);
            result.put("valid", validationResult.isValid());
            result.put("status", validationResult.getStatus());
            result.put("message", validationResult.getMessage());
            result.put("errors", validationResult.getErrors());
            result.put("ruleSetName", ruleSetName);
            result.put("dataType", dataType);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "测试数据校验异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取支持的校验规则类型
     * 
     * @return 支持的规则类型列表
     */
    @GetMapping("/supported-rule-types")
    public Map<String, Object> getSupportedRuleTypes() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<String> ruleTypes = Arrays.asList(
                "REQUIRED", "NOT_NULL", "NOT_EMPTY", "MIN_LENGTH", "MAX_LENGTH",
                "MIN_VALUE", "MAX_VALUE", "PATTERN", "EMAIL", "PHONE", "URL",
                "DATE", "IN_RANGE", "IN_LIST", "CUSTOM"
            );
            
            result.put("success", true);
            result.put("ruleTypes", ruleTypes);
            result.put("count", ruleTypes.size());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取支持的规则类型异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 生成测试数据
     * 
     * @param dataType 数据类型
     * @return 测试数据
     */
    private String generateTestData(String dataType) {
        switch (dataType.toLowerCase()) {
            case "user":
                return "{\"name\":\"张三\",\"email\":\"zhangsan@example.com\",\"phone\":\"13800138000\",\"age\":25}";
            case "product":
                return "{\"name\":\"测试产品\",\"price\":99.99,\"category\":\"电子产品\",\"stock\":100}";
            case "order":
                return "{\"orderId\":\"ORD001\",\"customerId\":\"CUST001\",\"amount\":199.99,\"status\":\"PENDING\"}";
            case "invalid":
                return "{\"name\":\"\",\"email\":\"invalid-email\",\"phone\":\"123\",\"age\":-1}";
            default:
                return "{\"message\":\"测试数据\"}";
        }
    }
}
